<template>
  <!-- 原有模板内容保持不变 -->
  <div style="margin-bottom: 15px;margin-left: 30px;">
    <el-input v-model="UserListVO.realName" style="width: 240px; padding-right: 15px;" placeholder="请输入姓名" />
    <el-input v-model="UserListVO.username" style="width: 240px;" placeholder="请输入账号" />
    <el-select v-model="UserListVO.rid" placeholder="请选择职务" style="width: 240px;padding-left: 15px;">
      <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
    <el-date-picker v-model="UserListVO.startTime" type="date" placeholder="起始时间" :size="size"
                    value-format="YYYY-MM-DD" format="YYYY-MM-DD" :disabled-date="disableStartDate"
                    style="margin-right: 10px;margin-left: 10px; width: 150px;" />
    <el-date-picker v-model="UserListVO.endTime" type="date" placeholder="结束时间" :size="size"
                    value-format="YYYY-MM-DD" format="YYYY-MM-DD" :disabled-date="disableEndDate" style="width: 150px;" />
    <el-icon @click="UserList()" style="margin-left: 20px; height: 25px; width: 25px;">
      <Search />
    </el-icon>
    <el-icon style="margin-left: 20px;" @click="RefreshUserListVO()">
      <Refresh />
    </el-icon>
    <el-button type="success" plain style="margin-left: 30px;" @click="userAddLook()">新建用户</el-button>
  </div>

  <el-table :data="tableData" style="width: 100%" stripe border="true">
    <el-table-column label="序号" width="100px" #default="scorp" align="center">
      {{ scorp.$index + 1 }}
    </el-table-column>
    <el-table-column prop="realName" label="姓名" width="180" align="center" />
    <el-table-column prop="username" label="账号" width="180" align="center" />
    <el-table-column prop="roleName" label="权限" width="180" align="center" />
    <el-table-column prop="email" label="邮箱" width="180" align="center" />
    <el-table-column prop="phone" label="手机号" width="180" align="center" />
    <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
    <el-table-column prop="status" label="状态" width="90" #default="scorp" align="center">
      <span v-if="scorp.row.status == 1" style="color: green;">启用</span>
      <span v-if="scorp.row.status == 0" style="color: red;">禁用</span>
    </el-table-column>
    <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scorp">
      <el-button type="warning" plain @click=" userAltLook(scorp.row)">修改</el-button>
      <el-button type="success" plain v-if="scorp.row.status == 0"
                 @click=StatusChange(scorp.row.id)>启用</el-button>
      <el-button type="info" plain v-if="scorp.row.status == 1" @click=StatusChange(scorp.row.id)>禁用</el-button>
      <el-button type="danger" plain @click="delUser(scorp.row.id)">删除</el-button>
    </el-table-column>
  </el-table>

  <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
    <el-pagination v-model:current-page="UserListVO.pageNum" v-model:page-size="UserListVO.pageSize"
                   :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="UserListVO.total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <el-dialog v-model="UserAdd" title="新建用户" width="500px" :before-close="handleClose" :close-on-click-modal="false"
             class="user-add-dialog">
    <el-form :model="user" label-width="100px" style="padding: 15px 0;" :rules="formRules" ref="userForm">
      <el-form-item label="姓名" prop="realName" class="form-item-custom">
        <el-input v-model="user.realName" placeholder="请输入真实姓名" clearable class="form-input-custom" />
      </el-form-item>

      <el-form-item label="用户名" prop="username" class="form-item-custom">
        <el-input v-model="user.username" placeholder="请设置登录用户名" clearable class="form-input-custom" />
      </el-form-item>

      <el-form-item label="密码" prop="password" class="form-item-custom">
        <el-input v-model="user.password" type="password" placeholder="请设置密码" show-password
                  class="form-input-custom" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email" class="form-item-custom">
        <el-input v-model="user.email" placeholder="请输入邮箱地址" clearable type="email" class="form-input-custom" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone" class="form-item-custom">
        <el-input v-model="user.phone" placeholder="请输入手机号码" clearable class="form-input-custom" />
      </el-form-item>

      <el-form-item label="权限" prop="rid" class="form-item-custom">
        <el-select v-model="user.rid" placeholder="请选择用户角色" clearable class="form-select-custom">
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status" class="form-item-custom">
        <el-radio-group v-model="user.status" class="status-radio-group">
          <el-radio value="1" size="small" class="status-radio">
            <span class="status-active">启用</span>
          </el-radio>
          <el-radio value="0" size="small" class="status-radio">
            <span class="status-disabled">禁用</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="default" class="cancel-btn">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm" size="default" class="confirm-btn">
          确认添加
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- ------------------------------------修改-------------------------------------------- -->
  <el-dialog v-model="UserAlt" title="新建用户" width="500px" :before-close="handleClose" :close-on-click-modal="false"
             class="user-add-dialog">
    <el-form :model="user" label-width="100px" style="padding: 15px 0;" :rules="formRules" ref="userForm">
      <el-form-item label="姓名" prop="realName" class="form-item-custom">
        <el-input v-model="user.realName" placeholder="请输入真实姓名" clearable class="form-input-custom" />
      </el-form-item>

      <el-form-item label="用户名" prop="username" class="form-item-custom">
        <el-input v-model="user.username" placeholder="请设置账号" clearable class="form-input-custom" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" class="form-item-custom">
        <el-input v-model="user.email" placeholder="请输入邮箱地址" clearable type="email" class="form-input-custom" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone" class="form-item-custom">
        <el-input v-model="user.phone" placeholder="请输入手机号码" clearable class="form-input-custom" />
      </el-form-item>
      <el-form-item label="权限" prop="rid" class="form-item-custom">
        <el-select v-model="user.rid" placeholder="请选择用户角色" clearable class="form-select-custom"
                   :disabled="user.rid == 1">
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status" class="form-item-custom">
        <el-radio-group v-model="user.status" class="status-radio-group" :disabled="user.rid == 1">
          <el-radio :value=1 size="small" class="status-radio">
            <span class="status-active">启用</span>
          </el-radio>
          <el-radio :value=0 size="small" class="status-radio">
            <span class="status-disabled">禁用</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="default" class="cancel-btn">
          取消
        </el-button>
        <el-button type="primary" @click="altitForm()" size="default" class="confirm-btn">
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { RoleListJS, UserAddJS, UserDelJS, UserListJS, UserStatusAltJS, UserUpdateJS } from '@/api/sys/user_sys';

import {
  Search,
  Refresh,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, getCurrentInstance } from 'vue';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 表格数据
const tableData = ref([])
// 用户分页参数
const UserListVO = ref({
  pageNum: 1,
  pageSize: 10,
  username: "",
  realName: "",
  rid: "",
  total: 0,
  startTime: "",
  endTime: ""
})

// 查询所有
function UserList() {
  UserListJS(UserListVO.value).then(res => {
    // 添加空值检查和错误处理
    if (res && res.data) {
      tableData.value = res.data.records || []
      UserListVO.value.total = res.data.total || 0
    } else {
      // 如果响应结构不同，尝试直接访问
      tableData.value = res?.records || []
      UserListVO.value.total = res?.total || 0
    }
  }).catch(error => {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    tableData.value = []
    UserListVO.value.total = 0
  })
}
UserList()

// 分页
const handleSizeChange = (val) => {
  UserListVO.value.pageSize = val;
  UserList()
}
const handleCurrentChange = (val) => {
  UserListVO.value.pageNum = val;
  UserList()
}

// 重置查询参数
function RefreshUserListVO() {
  UserListVO.value.username = ""
  UserListVO.value.rid = ""
  UserListVO.value.endTime = ""
  UserListVO.value.startTime = ""
  UserListVO.value.realName = ""
  UserList()
}

// 权限存储
const roleList = ref([])
// 权限查询
function RoleList() {
  RoleListJS().then(res => {
    // 添加空值检查
    if (res && res.data) {
      roleList.value = res.data
    } else {
      roleList.value = res || []
    }
  }).catch(error => {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
    roleList.value = []
  })
}
RoleList()

// 时间约束起始时间必须大于结束时间
const disableStartDate = (time) => {
  if (UserListVO.value.endTime) {
    return time > new Date(UserListVO.value.endTime)
  }
  return false
}
const disableEndDate = (time) => {
  if (UserListVO.value.startTime) {
    const start = new Date(UserListVO.value.startTime)
    return time < start
  }
  return false
}

function StatusChange(uid) {
  UserStatusAltJS(uid).then(res => {
    const message = res?.data || res || "操作完成"
    if (message == "管理员不能被禁用") {
      ElMessage.error(message)
    } else {
      ElMessage.success(message)
    }
    UserList()
  }).catch(error => {
    console.error('状态修改失败:', error)
    ElMessage.error('状态修改失败')
  })
}

function delUser(uid) {
  // 显示确认对话框
  ElMessageBox.confirm(
      '确定要删除该用户吗？此操作不可撤销。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    UserDelJS(uid).then(res => {
      const message = res?.data || res || "操作完成"
      if (message == "删除成功") {
        ElMessage.success(message)
        UserList()
      } else {
        ElMessage.error(message)
      }
    }).catch(error => {
      ElMessage.error('删除请求失败，请稍后重试')
      console.error('删除失败:', error)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const UserAdd = ref(false)
const user = ref({
  username: "",
  password: "",
  email: "",
  phone: "",
  realName: "",
  rid: "",
  status: ""
})

// 表单验证规则
const formRules = ref({
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  rid: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
})

function userAddLook() {
  UserAdd.value = true

}

function handleClose() {
  UserAdd.value = false
  UserAlt.value = false
  // 重置表单
  proxy.$refs.userForm.resetFields()
  user.value = {
    username: "",
    password: "",
    email: "",
    phone: "",
    realName: "",
    rid: "",
    status: ""
  }
  UserList()
}

// 提交表单前先进行验证
function submitForm() {
  proxy.$refs.userForm.validate((valid) => {
    if (valid) {
             UserAddJS(user.value).then(res => {
         const message = res?.data || res || "操作完成"
         if (message == "注册成功") {
           ElMessage.success(message)
           handleClose()
           UserList()
         } else {
           ElMessage.error(message)
         }
       }).catch(error => {
         console.error('添加用户失败:', error)
         ElMessage.error('添加用户失败')
       })
    } else {
      ElMessage.warning('请完善用户信息并确保格式正确')
      return false
    }
  })
}
const UserAlt = ref(false)
function userAltLook(row) {
  UserAlt.value = true
  user.value = row
}
function altitForm() {
  UserUpdateJS(user.value).then(res => {
    const message = res?.data || res || "操作完成"
    if (message == "修改成功") {
      ElMessage.success("修改成功")
      handleClose()
    } else {
      ElMessage.error("修改失败")
    }
  }).catch(error => {
    console.error('修改用户失败:', error)
    ElMessage.error('修改用户失败')
  })
}
</script>

<style>
.user-add-dialog {
  --el-dialog-padding-primary: 20px;
}

.form-item-custom {
  margin-bottom: 18px;
  transition: all 0.2s ease;
}

.form-item-custom:hover {
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.form-input-custom,
.form-select-custom {
  width: 320px;
  transition: border-color 0.2s ease;
}

.form-input-custom:focus-within,
.form-select-custom:focus-within {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(48, 163, 255, 0.2);
}

.status-radio-group {
  display: flex;
  gap: 20px;
  padding-top: 5px;
}

.status-radio {
  padding: 5px 15px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

/* 错误提示样式优化 */
.el-form-item__error {
  font-size: 12px;
  padding-top: 4px;
}
</style>
